/**
 * @param 路由相关中间件
 */
const userDao = require('../dao/user')
module.exports = function (router) {
  router.use((req, res, next) => {
    // 获取username 和 password
    let {username, password} = req.body
    // 验证用户名
    if (!/^[a-zA-Z][0-9a-zA-Z]{3,10}$/.test(username)) {
      next('用户名只能是数字、字母，长度4到10位')
    } else if (!/^\S{6,12}$/.test(password)) {
      next('密码6-12位，且不能出现空格')
    } else {
      next()
    }
  })
  // 验证token
  router.use( async (req, res, next) => {
    if (req.user && req.user.id) {
      let result = req.headers.authorization.split(' ')
      const resData = await userDao.verifyToken(req.user.id)
      if (resData && resData.token == result[1]) {
        next()
      } else {
        next('令牌不对或失效，请登录替换令牌')
      }
    } else {
      next()
    }
  })
  // 加载路由文件 --路由级中间件,目的是减少查找请求路径
  router.use((req, res, next) => {
    let location = req.path.split('/')
    if (location[1] === 'category') {
      require('../routes/category')(router)
      next()
    } else if (location[1] === 'user') {
      require('../routes/user')(router)
      next()
    } else if (location[1] === 'verify') {
      require('../routes/verify')(router)
      next()
    }
  })

  // 处理路由错误中间件
  // router.use((err, req, res, next) => {
  //   res.status(400).json({code: 400, msg: err})
  // })
}